<template>
  <!-- 否定关键词 -->

  <div v-loading="loading" :element-loading-text="loadingText">
    <div v-show="!checkedList.length" class="table-choose-box flex">
      <ul class="set flex">
        <li v-if="routeName==='seriesOverview'">
          <span class="title">
            类型
          </span>
          <div>
            <el-select v-model="queryData.type" placeholder="请选择" size="small" @change="queryDataChange">
              <el-option label="全部" value="all" />
              <el-option label="广告系列" value="campaign" />
              <el-option label="广告组" value="adGroup" />
            </el-select>
          </div>
        </li>

        <li v-if="routeName==='seriesOverview'&&queryData.type==='adGroup'">
          <span class="title">
            广告组
          </span>
          <div>
            <el-select v-model="queryData.adgroupId" placeholder="请选择" size="small" @change="queryDataChange">
              <el-option label="全部广告组" value="" />
              <el-option v-for="(item,index) in allAdList" :key="item.adGroupId" :label="item.name" :value="item.adGroupId" />
            </el-select>
          </div>
        </li>

        <li>
          <span class="title">
            匹配类型
          </span>
          <div>
            <el-select v-model="queryData.matchType" placeholder="请选择" size="small" @change="queryDataChange">
              <el-option label="全部类型" value="" />
              <el-option label="模糊匹配" value="BROAD" />
              <el-option label="精确匹配" value="EXACT" />
            </el-select>
          </div>
        </li>

        <li>
          <div>
            <el-input v-model="queryData.name" size="small" placeholder="搜索屏蔽词" @keyup.enter.native="queryDataChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="queryDataChange" />
            </el-input>

          </div>
        </li>
      </ul>
      <div />

      <div class="handle">
        <em
          v-if="!$isReadOnly(this.$store.state.user.userInfo.roleName)&&caInfo.displayStatus !=='DELETED'&&adInfo.displaystatus !=='DELETED'"
          @click="putShow=true"
        >添加屏蔽词</em>
        <em
          v-if="!$isReadOnly(this.$store.state.user.userInfo.roleName)&&caInfo.displayStatus !=='DELETED'&&adInfo.displaystatus !=='DELETED'"
          @click="dialogVisible=true"
        >上传屏蔽词</em>
        <em @click="dowLoadCsv">导出数据</em>
      </div>
    </div>

    <!-- 屏蔽词不能暂停 -->
    <table-batch-handle
      v-show="checkedList.length"
      :num="checkedList.length"
      :start-show="false"
      :pause-show="false"
      @batchDel="handleDelNoKeywords"
    />

    <el-table
      :data="tableData"
      style="width: 100%;margin-top: 14px;"
      class="series-table"
      :header-cell-class-name="headerStyle"
      @selection-change="tableCheckChange"
    >
      >
      <el-table-column
        v-if="selectBtnShow&&caInfo.displayStatus !=='DELETED'&&adInfo.displaystatus !=='DELETED'"
        type="selection"
        width="45"
        :selectable="(row, index)=>{return (row.deleted==='false')}"
      />
      <el-table-column label="屏蔽词" prop="text" align="left" fixed="left">
        <template slot-scope="scope">
          <div class="pointer" v-html="replaceKeyWord(scope.row.text,scope.row.matchType)"></div>
        </template>
      </el-table-column>

      <el-table-column v-if="routeName === 'seriesOverview'" label="类型" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.source==='adGroup'" class="pointer" @click="handlePush(scope.row.adGroupId)">广告组</span>
          <span v-else>广告系列</span>
        </template>
      </el-table-column>

      <el-table-column v-if="routeName === 'seriesOverview'" label="广告组" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.source==='adGroup'" class="pointer" @click="handlePush(scope.row.adGroupId)">{{ scope.row.adGroupName }}</span>
          <span v-else>--</span>
        </template>
      </el-table-column>

      <el-table-column label="匹配类型" align="center">
        <template slot-scope="scope">
          <p style="text-align: center;width: 100%;">{{ scope.row.matchType==="EXACT"?'精确匹配':'模糊匹配' }}</p>
        </template>
      </el-table-column>

    </el-table>

    <div class="block" style="padding-top: 24px;display: flex;justify-content: flex-end;">
      <el-pagination
        :current-page="queryData.pageNum"
        :page-sizes="[10,20,30,40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加否定关键词 手动-->
    <word-box ref="addNoWordBox" :visible.sync="putShow" title="屏蔽词" :before-sub="handleBeforeUPWord" @handleSub="handleSubKey">
      <div style="overflow: hidden;">
        <div v-if="routeName==='seriesOverview'">
          <p>
            <span>添加至</span>
          </p>
          <div style="padding: 16px 0;display: flex; align-items: center; justify-content: space-between; width: 360px;">
            <div>
              <el-radio v-model="negateAddType" label="group">广告组</el-radio>
              <el-radio v-model="negateAddType" label="series">广告系列</el-radio>
            </div>
            <em v-if="negateAddGroupList.length<allAdList.length&&negateAddType=='group'" class="pointer" @click="handlePushAll">添加全部</em>
            <em v-if="negateAddGroupList.length>=allAdList.length&&negateAddType=='group'" class="pointer" @click="negateAddGroupList=[]">移除全部</em>
          </div>

        </div>

        <div v-if="routeName==='seriesOverview'&&negateAddType==='group'" style="padding-bottom: 20px;">
          <el-select v-model="negateAddGroupList" placeholder="请选择" size="small" multiple style="width: 360px;" @change="queryDataChange">
            <el-option v-for="(item,index) in allAdList" :key="item.adGroupId" :label="item.name" :value="item.adGroupId" />
          </el-select>
        </div>
      </div>

    </word-box>

    <!-- 添加否定关键词  批量-->
    <up-load-words
      title="添加屏蔽词"
      :is-negative="true"
      :visible.sync="dialogVisible"
      :before-upload="handleBeforeUPWord"
      @handleAddWords="handleSubKey"
    >
      <div v-if="routeName==='seriesOverview'" style="width: 100%;padding-left: 28px;">
        <p>
          <span>添加至</span>

        </p>
        <div style="padding: 16px 0;display: flex; align-items: center; justify-content: space-between; width: 360px;">
          <div>
            <el-radio v-model="negateAddType" label="group">广告组</el-radio>
            <el-radio v-model="negateAddType" label="series">广告系列</el-radio>
          </div>
          <em v-if="negateAddGroupList.length<allAdList.length&&negateAddType=='group'" class="pointer" @click="handlePushAll">添加全部</em>
          <em v-if="negateAddGroupList.length>=allAdList.length&&negateAddType=='group'" class="pointer" @click="negateAddGroupList=[]">移除全部</em>
        </div>
      </div>
      <div v-if="routeName==='seriesOverview'&&negateAddType==='group'" style="padding: 0 0 20px 28px;display: flex;justify-content: flex-start;width: 100%;">
        <el-select v-model="negateAddGroupList" placeholder="请选择" size="small" multiple style="width: 90%;" @change="queryDataChange">
          <el-option v-for="(item,index) in allAdList" :key="item.adGroupId" :label="item.name" :value="item.adGroupId" />
        </el-select>
      </div>
    </up-load-words>
  </div>
</template>

<script>
import tableBatchHandle from '../../components/table-batch-handle/index.vue'
import wordBox from '@/components/word-box.vue'
import upLoadWords from './upLoadWords.vue'
import {
  findNegativeKeyWordsList, // 查询广告系列组下的否定表格；
  downloadNegativeKeyWordsCsv, // 下载屏蔽词表格；
  addNegativeKeyWords, // 添加屏蔽词到广告组；
  addCampaignsNegativeKeyWords, // 添加屏蔽词到广告系列
  removeNegativeKeyWords, // 删除广告组屏蔽词；
  removeCampaignsNegativeKeyWords, // 删除广告系列屏蔽词；
  modifyKeyWords // 修改关键词

} from '@/api/keyWord.js'

export default {
  components: {
    tableBatchHandle,
    wordBox,
    upLoadWords
  },
  props: {},

  data() {
    return {
      negateAddGroupList: [], // 添加屏蔽词到广告组时选中的广告组
      negateAddType: 'group', // 添加屏蔽词到广告组or广告系列  group：广告组  series:广告系列
      searchType: 'all',
      loading: false,
      loadingText: '数据加载中，请稍候',
      dialogVisible: false,
      csvUrl: '', // 模板下载路径
      /* 批量修改最高每次点击费用*/
      popoNunmber: undefined,
      popoShow: false,
      // 关键词添加
      putShow: false,
      keywords: [],
      // 关键词上传
      thVisible: false, // 设置字段的显示
      checkedList: [], // 选中的
      tableData: [],
      totalData: [],
      total: 0,
      queryData: {
        teamId: this.$store.state.team.teamId || '',
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
        currencyType: this.$route.query.currencyType || this.$store.state.user.unit,
        adgroupId: this.$route.query.adgroupId || this.$route.query.adGroupId || '',
        campaignId: '',
        startTime: this.$store.state.overview.timeObj.overViewTime.startTime,
        endTime: this.$store.state.overview.timeObj.overViewTime.endTime,
        name: '',
        order: 'descending',
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        pageNum: 1,
        pageSize: 10,
        prop: 'status', // 选择项
        status: '',
        matchType: '',
        type: 'all'

      }
    }
  },
  computed: {
    routeName() {
      return this.$route.name
    },
    // 选择的开始时间与结束时间
    timeObj() {
      return this.$store.state.overview.timeObj.overViewTime
    },
    // 广告组详情
    adInfo() {
      if (this.$route.name === 'seriesOverview') {
        return {
          displayStatus: this.caInfo.displayStatus
        }
      }
      const arr = this.$store.state.overview.allAd
      const index = arr.findIndex(item => {
        return item.adGroupId * 1 === this.$route.query.adGroupId * 1
      })
      return arr[index]
    },
    // 广告系列详情
    caInfo() {
      const arr = this.$store.state.overview.allCa
      const index = arr.findIndex(item => {
        return item.campaignId * 1 === this.$route.query.campaignId * 1
      })
      return arr[index]
    },
    allAdList() {
      return this.$store.state.overview.allAd
    },
    timeZone() {
      return this.$store.state.user.timeZone
    },
    selectBtnShow() {
      if (this.$route.query.uuid && (this.$route.query.orgId || this.$route.query.orgid)) {
        const index = this.$store.state.overview.allAc.findIndex(item => {
          return item.uuid === this.$route.query.uuid
        })
        if (this.$store.state.overview.allAc[index].roleName === 'invalid_client') {
          return false
        }

        const i = this.$store.state.overview.allAc[index].org.findIndex(item => {
          return item.orgId === this.$route.query.orgId * 1 || item.orgId === this.$route.query.orgid * 1
        })
        const orgRole = this.$store.state.overview.allAc[index].org[i].roleName
        return orgRole !== 'API Read Only' && !this.$isReadOnly(this.$store.state.user.userInfo.roleName)
      } else {
        return !this.$isReadOnly(this.$store.state.user.userInfo.roleName)
      }
    }
  },
  watch: {
    timeObj: {
      handler: function(newval, oldval) {
        if (newval.length) {
          this.queryData.pageNum = 1
          this.queryData.startTime = newval.startTime
          this.queryData.endTime = newval.endTime
          this.findNegativeKeyWordsList()
        } else {
          return false
        }
      },
      immediate: true,
      deep: true
    },

    timeZone: {
      deep: true,
      handler: function(newV, oldV) {
        this.queryData.pageNum = 1
        this.findNegativeKeyWordsList()
      }
    }

  },
  mounted() {
    this.findNegativeKeyWordsList()
  },

  methods: {
    replaceKeyWord(word, type) {
      const str = word.replace(/\ /g, '&nbsp;')
      if (type === 'EXACT') return '[' + str + ']'
      return str
    },
    headerStyle({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      if (columnIndex === 3) {
        return 'right-align'
      }
    },
    handlePushAll() {
      if (this.allAdList.length) {
        this.negateAddGroupList = this.allAdList.map(item => {
          return item.adGroupId
        })
      } else {
        return false
      }
    },

    // 去广告组详情
    handlePush(id) {
      this.$router.push({
        name: 'groupOverview',
        query: {
          ...this.$route.query,
          adGroupId: id
        }
      })
    },

    // 添加||上传屏蔽词之前所在的验证
    handleBeforeUPWord() {
      if (this.negateAddType === 'group' && this.negateAddGroupList.length === 0 && this.routeName ===
          'seriesOverview') {
        this.$message.closeAll()
        this.$message.error('请先选择广告组')
        return false
      }
      return true
    },

    // 勾选数据
    tableCheckChange(data) {
      this.checkedList = JSON.parse(JSON.stringify(data))
    },

    /* 批量操作 */

    // 批量移除屏蔽词
    handleDelNoKeywords() {
      const AdArr = []
      const CaArr = []
      this.checkedList.forEach(item => {
        if (item.source === 'adGroup') {
          AdArr.push(item)
        } else {
          CaArr.push(item.keywordId)
        }
      })

      if (AdArr.length) {
        this.delAdNoKeywords(AdArr)
      }

      if (CaArr.length) {
        this.delCANoKeywords((CaArr))
      }
    },

    // 广告组屏蔽词删除
    async delAdNoKeywords(arr) {
      this.loading = true
      this.loadingText = '数据正在删除中，请稍候'
      const delArr = []
      arr.forEach(item => {
        const index = delArr.findIndex(v => {
          return v.adGroupId === item.adGroupId
        })
        if (index === -1) {
          const obj = {
            teamId: this.$store.state.team.teamId || '',
            orgId: this.$route.query.orgId || '', // 如果是自助投放为空
            uuid: this.$route.query.uuid || '',
            aId: this.$route.query.aId || this.$route.query.aid || '',
            userId: this.$store.state.user.userInfo.userId,
            campaignId: item.campaignId,
            adGroupId: item.adGroupId,
            keywords: [item.keywordId],
            currencyType: this.$route.query.currencyType || this.$store.state.user.unit
          }

          delArr.push(obj)
        } else {
          delArr[index].keywords.push(item.keywordId)
        }
      })
      const res = await removeNegativeKeyWords([...delArr])
      if (res.data.code && res.data.code === 20000) {
        this.loadingText = '数据删除成功，正在更新数据'

        setTimeout(() => {
          this.queryData.pageNum = 1
          this.findNegativeKeyWordsList()
        }, 3500)
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误,请稍候重试')
      }
      this.loading = false
    },

    // 广告系列屏蔽词删除
    async delCANoKeywords(arr) {
      this.loading = true
      this.loadingText = '数据正在删除中，请稍候'
      const obj = {
        teamId: this.$store.state.team.teamId || '',
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        userId: this.$store.state.user.userInfo.userId,
        campaignId: this.$route.query.campaignId * 1,
        adGroupId: this.$route.query.adGroupId * 1,
        keywords: arr,
        currencyType: this.$route.query.currencyType || this.$store.state.user.unit
      }
      const res = await removeCampaignsNegativeKeyWords(obj)
      if (res.data.code && res.data.code === 20000) {
        this.loadingText = '数据删除成功，正在更新数据'
        setTimeout(() => {
          this.findNegativeKeyWordsList()
        }, 3500)
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误,请稍候重试')
      }
      this.loading = false
    },

    // 添加屏蔽词
    handleSubKey(data) {
      if (!data.length) return false
      if (this.negateAddType === 'group') {
        this.addNegativeKeyWordsToAdgroup(data)
      } else {
        this.addNegativeKeyWordsToSeries(data)
      }
    },
    // 添加屏蔽词到广告组
    async addNegativeKeyWordsToAdgroup(data) {
      const adGroupList = this.$route.name === 'seriesOverview' ? this.negateAddGroupList : [this.$route.query.adGroupId]
      const arr = adGroupList.map(item => {
        const obj = {
          teamId: this.$store.state.team.teamId || '',
          campaignId: this.$route.query.campaignId || this.$route.query.campaignid,
          adGroupId: item,
          orgId: this.$route.query.orgId || '', // 如果是自助投放为空
          uuid: this.$route.query.uuid || '',
          aId: this.$route.query.aId || this.$route.query.aid || '',
          userId: this.$store.state.user.userInfo.userId,
          negativeKeyword: JSON.parse(JSON.stringify(data)),
          currencyType: this.$route.query.currencyType || this.$store.state.user.unit
        }
        return obj
      })

      const res = await addNegativeKeyWords(arr)
      this.$refs['addNoWordBox'].wordsData = []
      if (res.data.code && res.data.code === 20000) {
        this.loading = true
        this.loadingText = '添加成功，数据更新中。请稍候'
        setTimeout(() => {
          this.findNegativeKeyWordsList()
        }, 3500)
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误，请稍后重试')
      }
      this.loading = false
    },

    // 添加屏蔽词到广告系列
    async addNegativeKeyWordsToSeries(data) {
      const {

        campaignId
      } = this.$route.query
      const obj = {
        teamId: this.$store.state.team.teamId || '',
        campaignId,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        userId: this.$store.state.user.userInfo.userId,
        campaignNegativeKeyword: JSON.parse(JSON.stringify(data)),
        currencyType: this.$route.query.currencyType || this.$store.state.user.unit
      }
      const res = await addCampaignsNegativeKeyWords(obj)
      this.$refs['addNoWordBox'].wordsData = []
      if (res.data.code && res.data.code === 20000) {
        this.loading = true
        this.loadingText = '添加成功，数据更新中。请稍候'
        setTimeout(() => {
          this.findNegativeKeyWordsList()
        }, 3500)
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误，请稍后重试')
      }
    },

    // 下面是表格操作啦
    handleSizeChange(index) {
      this.queryData.pageSize = index
      this.queryData.pageNum = 1
      this.findNegativeKeyWordsList()
    },
    handleCurrentChange(index) {
      this.queryData.pageNum = index
      this.findNegativeKeyWordsList()
    },
    queryDataChange() {
      this.queryData.pageNum = 1
      this.findNegativeKeyWordsList()
    },

    // 查询屏蔽词
    async findNegativeKeyWordsList() {
      this.loading = true
      this.loadingText = '数据加载中，请稍候'

      const obj = {
        ...this.queryData,
        teamId: this.$store.state.team.teamId || '',
        campaignId: this.$route.query.campaignId || ''
      }
      if (this.routeName !== 'seriesOverview') {
        obj.type = 'adGroup'
      }

      const res = await findNegativeKeyWordsList(obj)

      if (res.data.code && res.data.code === 20000) {
        const {
          data
        } = res.data
        this.total = data.total
        this.tableData = JSON.parse(JSON.stringify(data.list))
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误，请稍后重试')
      }
      this.loading = false
    },

    // 设置显示字段
    thShowChange() {
      this.thVisible = true
    },

    handleSubThList(arr, type) {
      localStorage.setItem('3yData_keyWords_Thlist', JSON.parse(JSON.stringify(arr)))
    },
    // 导出数据
    async dowLoadCsv() {
      if (this.total < 1) {
        this.$message.closeAll()
        this.$message.error('请先添加屏蔽词')
        return false
      }
      const res = await downloadNegativeKeyWordsCsv({
        ...this.queryData,
        pageNum: 1,
        pageSize: this.total,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        teamId: this.$store.state.team.teamId || '',
        campaignId: this.$route.query.campaignId || '',
        currencyType: this.$route.query.currencyType || this.$store.state.user.unit
      })

      if (!res.data.message) {
        const blob = new Blob(['\ufeff' + res.data], {
          type: 'text/csv,charset=UTF-8'
        })
        const that = this
        const objectUrl = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.setAttribute('href', objectUrl)
        a.setAttribute('download', 'YYY_DATA_屏蔽词_' + that.queryData.startTime + '_' + this.queryData.endTime +
            '.csv')
        a.click()
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '导出数据失败，请稍后重试')
      }
    }

  }

}
</script>

<style lang="scss" scoped>
  @import '../../components/handle.scss';
</style>
